package client;

import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import interfaces.*;

public class ClientMediator extends Mediator {
	private Client client;
	private ClientSocketHandler socket;
	private int clientId = -1;
	
	public ClientMediator(){
		
	}

	
	
	public Client getClient() {
		return client;
	}



	public void setClient(Client client) {
		this.client = client;
	}



	public ClientSocketHandler getSocket() {
		return socket;
	}



	public void setSocket(ClientSocketHandler socket) {
		this.socket = socket;
	}



	public int getClientId() {
		return clientId;
	}



	public void setClientId(int clientId) {
		this.clientId = clientId;
	}



	/**
	 * retreive client id from server
	 */
	public void retreiveId(){
		socket.notify("__ID");
		analyze(socket, socket.listen());
	}
	
	/**
	 * display user id to user
	 */
	public void showId(){
		
		if(clientId < 0){
			client.display("ID retreive error!");
			return;
		}
		client.display("Your ID is: " + clientId + "\n");
	}
	
	
	/**
	 * analyze
	 */
	public boolean analyze(SocketHandler socketH, String input){
       	String[] contentTmp = input.split(separator);
       	String content = new String();      	
       	
       	int sourceClientId = -1;
       	
       	String command = contentTmp[0];
       	
    	if(contentTmp.length < 2){
    		client.display("Retrieving data error");
    	}
    	
    	else if(command.equals(ID_ASSIGN)){
    		String id = contentTmp[1];
    		clientId = Integer.parseInt(id);
    		client.setId(clientId);
    		socket.setSocketId(clientId);
    	}
    	
    	else if(command.equals(NEW_CLIENT)){
    		client.display(contentTmp[1]);
    	}
    	
    	else if(command.equals(MSG_ALL)){
    		//get from broad cast
    		sourceClientId = Integer.parseInt(contentTmp[1]);
        	content = contentTmp[2];
        	if(sourceClientId < 0){
        		client.display("From Server to you(#"+clientId+") :" + content + "\n");
        	}
        	else{
        		client.display("(Broadcast)From client #"+ sourceClientId + " to you(#"+clientId+") :" + content + "\n");
        	}
    	} 
    	else if(command.equals(MSG_OUT_ALL)){
    		//send out to all
    		content = contentTmp[1];
    		client.display("You said: " + content + "\n");
    		String send = MSG_ALL + separator + content;
    		socket.notify(send);
    		if(content.equals("bye")){
    			socket.close();
    			return false;
    		}
    	}
    	return true;
	}
	
}
